package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.UsersService;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Purchase;
import com.joint.core.service.PurchaseService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/27.
 */
@ParentPackage("manage")
public class AjaxPurchaseAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private UsersService usersService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private DepartmentService departmentService;

    /**
     * 资产类别,1 低值易耗品，2 固定资产
     */
    private String assetType;
    private String assetTypeText;
    /**
     * 采购类别
     */
    private String purchaseType;
    private String purchaseTypeText;
    /**
     * 申请部门
     */
    private String departmentId;
    /**
     * 采购详情json
     */
    private String purchaseDetail;
    /**
     * 合计json
     */
    private String detailNum;
    /**
     * 其他需要说明情况
     */
    private String other;
    /**
     * 支付方式，1 转账，2 现金
     */
    private String pay;
    private String payText;
    /**
     * 收款方名称
     */
    private String toName;
    /**
     * 收款方账号
     */
    private String toNo;
    /**
     * 是否需要上报中心
     */
    private int leaderExam;
    /**
     * 是否是产业中心人员
     */
    private int ifCentralStaff;

    private Purchase purchase;
    private int numStatus;
    private Users loginUser;
    private String step;
    private String assetuse;
    private String assetuseId;
    private String expend;
    private String expendId;

    public String execute(){
        return "purchase";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
      //  params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(step)){
            if(step.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("step","1");
                pager=purchaseService.findByPagerAndLimit(false, "purchase", pager, params);
            }else if(step.equals("2")){
                //待采购
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("step","2");
                pager=purchaseService.findByPagerAndLimit(false, "purchase", pager, params);
            }else if(step.equals("3")){
                //采购完成
                params.put("step","3");
                pager=purchaseService.findByPagerAndFinish("purchase", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=purchaseService.findByPagerAndLimit(true, "purchase", pager, params);
        }

        List<Purchase> purchaseList;
        if (pager.getTotalCount() > 0){
            purchaseList = (List<Purchase>) pager.getList();
        }else{
            purchaseList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Purchase purchase: purchaseList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",purchase.getId());
            rMap.put("year",DataUtil.DateToString(purchase.getCreateDate(), "yyyy"));
            rMap.put("month",DataUtil.DateToString(purchase.getCreateDate(), "MM"));
            rMap.put("department",purchase.getDepartment().getName());
            rMap.put("creater", purchase.getCreater() != null ? purchase.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(purchase.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",purchase.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            purchase=purchaseService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
        }
        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            purchase = purchaseService.get(keyId);
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            purchase=purchaseService.get(keyId);
        }else{
            purchase=new Purchase();
            purchase.setCreater(usersService.getLoginInfo());
        }
        purchase.setAssetType(assetType);
        purchase.setPurchaseType(purchaseType);
        purchase.setDepartment(departmentService.get(departmentId));
        purchase.setPurchaseDetail(purchaseDetail);
        purchase.setDetailNum(detailNum);
        purchase.setOther(other);
        purchase.setPay(pay);
        purchase.setToName(toName);
        purchase.setToNo(toNo);
        purchase.setCompany(usersService.getLoginInfo().getCompany());
        purchase.setStep("1");
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                purchaseService.update(purchase);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                purchaseService.save(purchase, "purchase", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        List<String> thisapplyList= Lists.newArrayList();
        Users creater=usersService.getLoginInfo();
        thisapplyList.add(creater.getId());

        var1.put("thisapply", thisapplyList);
        var2.put("thisapply", thisapplyList);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var2, curDutyId, comment);
            } else {
                keyId = purchaseService.commit(purchase, "purchase", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        ifCentralStaff=0;
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        Set<Duty> dutySet = purchase.getCreater().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus",2);
        }
        var1.put("ifCentralStaff", ifCentralStaff);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批2
    public String approve2(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        if(leaderExam==1){
            var1.put("numStatus", 3);
        }else{
            var1.put("numStatus", 5);
        }
        purchase.setLeaderExam(leaderExam == 1 ? true : false);
        var1.put("leaderExam", leaderExam);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批3
    public String approve3(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 4);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批4
    public String approve4(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 5);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //申请人审批5
    public String approve5(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 6);
        purchase.setStep("2");
        purchase.setPurchaseDetail(purchaseDetail);
        purchase.setDetailNum(detailNum);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("40" +
                    "4", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批6
    public String approve6(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 7);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批7
    public String approve7(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 8);
        var1.put("leaderExam", leaderExam);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                if(leaderExam==1){
                    purchaseService.approve(purchase, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
                }else{
                    purchase.setStep("3");
                    purchaseService.approve(purchase, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
                }

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批8
    public String approve8(){
        purchase = purchaseService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 9);
        purchase.setStep("3");
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                purchaseService.approve(purchase, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            purchase = purchaseService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("purchase");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            // System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            purchaseService.reject(purchase, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            purchase = purchaseService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("purchase");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            purchaseService.deny(purchase, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }


    public String getAssetType() {
        return assetType;
    }

    public void setAssetType(String assetType) {
        this.assetType = assetType;
    }

    public String getPurchaseType() {
        return purchaseType;
    }

    public void setPurchaseType(String purchaseType) {
        this.purchaseType = purchaseType;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getPurchaseDetail() {
        return purchaseDetail;
    }

    public void setPurchaseDetail(String purchaseDetail) {
        this.purchaseDetail = purchaseDetail;
    }

    public String getDetailNum() {
        return detailNum;
    }

    public void setDetailNum(String detailNum) {
        this.detailNum = detailNum;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }

    public String getPay() {
        return pay;
    }

    public void setPay(String pay) {
        this.pay = pay;
    }

    public String getToName() {
        return toName;
    }

    public void setToName(String toName) {
        this.toName = toName;
    }

    public String getToNo() {
        return toNo;
    }

    public void setToNo(String toNo) {
        this.toNo = toNo;
    }

    public int getLeaderExam() {
        return leaderExam;
    }

    public void setLeaderExam(int leaderExam) {
        this.leaderExam = leaderExam;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public Purchase getPurchase() {
        return purchase;
    }

    public void setPurchase(Purchase purchase) {
        this.purchase = purchase;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    public String getAssetTypeText() {
        return assetTypeText;
    }

    public void setAssetTypeText(String assetTypeText) {
        this.assetTypeText = assetTypeText;
    }

    public String getPurchaseTypeText() {
        return purchaseTypeText;
    }

    public void setPurchaseTypeText(String purchaseTypeText) {
        this.purchaseTypeText = purchaseTypeText;
    }

    public String getPayText() {
        return payText;
    }

    public void setPayText(String payText) {
        this.payText = payText;
    }

    public String getAssetuse() {
        return assetuse;
    }

    public void setAssetuse(String assetuse) {
        this.assetuse = assetuse;
    }

    public String getAssetuseId() {
        return assetuseId;
    }

    public void setAssetuseId(String assetuseId) {
        this.assetuseId = assetuseId;
    }

    public String getExpend() {
        return expend;
    }

    public void setExpend(String expend) {
        this.expend = expend;
    }

    public String getExpendId() {
        return expendId;
    }

    public void setExpendId(String expendId) {
        this.expendId = expendId;
    }
}
